<template>

  <el-tooltip :visible="!props.applyIsDisabled" class="box-item"
              content="请先点击（处方新增）按钮"
              effect="dark" placement="right">
    <el-button :disabled="!props.applyIsDisabled" plain style="margin-bottom: 5px" type="primary"
               @click="handleAddDrug">
      <template #icon>
        <i-ep-plus/>
      </template>
      添加药品(F2)
    </el-button>
  </el-tooltip>
  <el-button :disabled="!props.applyIsDisabled" plain style="margin-bottom: 5px" type="danger"
             @click="emptyDrugList(true)">
    <template #icon>
      <i-ep-delete-filled/>
    </template>
    清空
  </el-button>
  <el-form ref="formRef" :model="form" :rules="rules">
    <el-table v-adaptive="30" :border="true" :data="form.prescriptionItemList" :header-cell-style="$headerCellStyle"
              :stripe="true"
              highlight-current-row @selection-change="handleSelectionChange">
      <el-table-column :align="'center'" label="组号" prop="groupNumber" width="70">
        <template #default="scope">
          <el-form-item v-if="trDisabled" :prop="'prescriptionItemList.' + scope.$index + '.groupNumber'"
                        :rules="rules.groupNumber" class="table-form-margin">
            <el-input v-model="scope.row.groupNumber"
                      v-keyupEnter="{ index: scope.$index, name: 'groupNumber' }" class="groupNumber"
                      clearable
                      type="number"
                      @blur="groupNumberBlur(scope.$index, scope.row)"></el-input>
          </el-form-item>
          <span v-else>{{ scope.row.groupNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column :align="'left'" label="药品" min-width="140" prop="drugName">
        <template #default="scope">
          <el-form-item v-if="trDisabled" :prop="'prescriptionItemList.' + scope.$index + '.drugName'"
                        :rules="rules.drugName" class="table-form-margin">
            <automatic-completion :ref="(el:any) => setItemAutomaticRef(el, scope.$index)" :dict-array="dictArray" :table-body-list="tableBodyList"
                                  :table-head-list="tableHeadList" :title="itemTitle"
                                  :right-div-show-type="'westernMedicine'" :width="978"
                                  style="width: 100%;" @itemNameInput="itemNameInput($event, scope.$index, scope.row)"
                                  @rowClick="rowClick($event, scope.$index, scope.row)"/>
          </el-form-item>
          <span v-else>{{ scope.row.groupNumberStyle }}<span
            class="ml5">{{ scope.row.drugName }}</span></span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="途径" prop="channel" width="100">
        <template #default="scope">
          <el-form-item v-if="trDisabled" :prop="'prescriptionItemList.' + scope.$index + '.channel'"
                        :rules="rules.channel" class="table-form-margin">
            <administration-index v-keyupEnter="{ index: scope.$index, name: 'channel' }"
                                  :disabled="scope.row.channelDisabled"
                                  :placeholder="'请选择途径'" :value="scope.row.channel"
                                  style="width: 100%"
                                  @administrationInfoChange="administrationInfoChange($event, scope.$index, scope.row)"/>
          </el-form-item>
          <span v-else>{{ scope.row.channelName }}<span v-if="scope.row.allergyResult"
                                                        :style="{color: scope.row.allergyResult!= '-' ?  '#ff0000' : '#159100',fontWeight:'bold'}"
                                                        class="ml5">({{
              scope.row.allergyResult
            }})</span></span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="单次用量" prop="singleDosage" width="120">
        <template #default="scope">
          <el-form-item v-if="trDisabled" :prop="'prescriptionItemList.' + scope.$index + '.singleDosage'"
                        :rules="rules.singleDosage" class="table-form-margin">
            <el-input v-model="scope.row.singleDosage" v-keyupEnter="{ index: scope.$index, name: 'singleDosage' }"
                      class="input-mr"
                      clearable
                      @blur="inputBlur(scope.$index)">
              <template #append>{{ scope.row.singleUnitName }}</template>
            </el-input>
          </el-form-item>
          <span v-else style="margin-left: -15px"> {{ scope.row.singleDosage }}<dict-data-tag
            :options="dictDataMap['dose_unit']" :value="scope.row.singleUnit"
            style="margin: -23px -20px 0px 35px"/></span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="频次" prop="performFreq" width="100">
        <template #default="scope">
          <el-form-item v-if="trDisabled" :prop="'prescriptionItemList.' + scope.$index + '.performFreq'"
                        :rules="rules.performFreq" class="table-form-margin">
            <perform-index ref="performIndex" v-keyupEnter="{ index: scope.$index, name: 'performFreq' }"
                           :disabled="scope.row.performFreqDisabled"
                           :placeholder="'请选择频次'"
                           :value="scope.row.performFreq"
                           style="width: 100%"
                           @performFreqInfoChange="performFreqInfoChange($event, scope.$index)"/>
          </el-form-item>
          <span v-else>{{ scope.row.performFreqName }}</span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="天数" prop="abidance" width="70">
        <template #default="scope">
          <el-form-item v-if="trDisabled" :prop="'prescriptionItemList.' + scope.$index + '.abidance'"
                        :rules="rules.abidance" class="table-form-margin">
            <el-input v-model="scope.row.abidance" v-keyupEnter="{ index: scope.$index, name: 'abidance' }"
                      class="input-mr"
                      clearable
                      @blur="inputBlur(scope.$index)"></el-input>
          </el-form-item>
          <span v-else>{{ scope.row.abidance }}</span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="数量" prop="num" width="90">
        <template #default="scope">
          <el-form-item v-if="trDisabled" :prop="'prescriptionItemList.' + scope.$index + '.num'"
                        :rules="rules.num" class="table-form-margin">
            <el-input v-model="scope.row.num" v-keyupEnter="{ index: scope.$index, name: 'num' }"
                      class="input-mr" clearable
                      @blur="numInputBlur(scope.$index)">
              <template #append>{{ scope.row.unitName }}</template>
            </el-input>
          </el-form-item>
          <span v-else>{{ scope.row.num }} <dict-data-tag :options="dictDataMap['spec_unit']" :value="scope.row.packSize === '1' ?
                        scope.row.minUnits : scope.row.packageUnits" style="margin: -23px -20px 0px 27px"/></span>
        </template>
      </el-table-column>
      <el-table-column v-if="!isOtcOutpatient" :align="'center'" label="免皮试" prop="noSkin" width="60px">
        <template #default="scope">
          <el-form-item v-if="trDisabled" class="table-form-margin noSkin-checkbox">
            <el-checkbox v-model="scope.row.noSkin"></el-checkbox>
          </el-form-item>
          <span v-else>
                        <dict-data-tag :options="dictDataMap['sys_yes_no']" :value="scope.row.noSkin"/>
                    </span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="单价" prop="price" width="75">
        <template #default="scope">
          {{ parseFloat(scope.row.price).toFixed(2) }}元
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="总价" prop="sumPrice" width="80">
        <template #default="scope">
          {{ parseFloat(scope.row.sumPrice).toFixed(2) }}元
        </template>
      </el-table-column>
      <el-table-column v-if="!isOtcOutpatient" :align="'center'" label="滴速" prop="dripSpeed" width="110px">
        <template #default="scope">
          <el-form-item v-if="trDisabled">
            <el-select v-model="scope.row.dripSpeed" v-keyupEnter="{ index: scope.$index, name: 'dripSpeed' }"
                       class="width-120" clearable
                       placeholder="请选择滴速"
                       @change="dripSpeedChange($event, scope.$index, scope.row)">
              <el-option v-for="dict in dictDataMap['sys_drop_speed']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"/>
            </el-select>
          </el-form-item>
          <span v-else><dict-data-tag :options="dictDataMap['sys_drop_speed']"
                                      :value="scope.row.dripSpeed"/></span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="批号" :align="'center'" width="80" prop="batchNo" :show-overflow-tooltip="true" /> -->
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="规格" prop="packageSpec"
                       width="140"/>
      <!-- <el-table-column :align="'center'" :show-overflow-tooltip="true" label="厂商" prop="firmName" width="91">
          <template #default="scope">
              <div>{{ scope.row.firmName }}</div>
          </template>
      </el-table-column> -->
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="医生说明" width="120px">
        <template #default="scope">
          <el-form-item v-if="trDisabled" class="table-form-margin">
            <el-input v-model="scope.row.remarks" v-keyupEnter="{ index: scope.$index, name: 'remarks' }"
                      class="input-mr"
                      clearable></el-input>
          </el-form-item>
          <span v-else>{{ scope.row.remarks }}</span>
        </template>
      </el-table-column>

      <el-table-column v-if="trDisabled" :align="'center'" class-name="small-padding fixed-width" fixed="right"
                       label="操作"
                       width="65">
        <template #default="scope">
          <el-tooltip class="item" content="删除" effect="dark" placement="top">
            <el-button circle type="danger" @click="handleDelete(scope.$index, scope.row)">
              <template #icon>
                <i-ep-delete/>
              </template>
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
</template>

<script setup lang="ts">
import {autoPrescriptionList} from "@/api/drug/drugStock.ts"
import {useDictStoreHook} from "@/store/modules/dict";
import {jsonStrInObj, prescriptionList} from "@/utils/autoComplete"
import {positiveNumberNotNull} from "@/utils/myRules.ts";
import {historyApplyQuote, listPrescriptionItem} from "@/api/patient/prescriptionItem.ts"
import {addPrescriptionApply} from "@/api/patient/prescriptionApply.ts";

const dictStore = useDictStoreHook();
let dictDataMap = ref(dictStore.isTypeGetData('spec_unit', 'sys_yes_no', 'dose_unit', 'sys_drop_speed'))
// 创建一个ref数组来存储每个automatic-completion实例
const itemAutomaticRefs = ref<any[]>([]);

// 在模板中使用动态ref
function setItemAutomaticRef(el, index) {
  if (el) {
    itemAutomaticRefs.value[index] = el;
  }
}
const {proxy} = getCurrentInstance() as any;
const emits = defineEmits(["itemSubmitOk", "submitOk"])
const trDisabled = ref<boolean>(true)
const props = defineProps({
  orgId: {
    type: String,
    default: ""
  },
  applyIsDisabled: {
    type: Boolean,
    default: true
  },
  // 是否来在OTC门诊  默认不是来自otc门诊
  isOtcOutpatient: {
    type: Boolean,
    default: true
  }
});
const formRef = ref()
// 表单参数
const form = ref<any>({
  // 药品list
  prescriptionItemList: []
})
const autoForm = ref<any>({
  drugClassArray: null,
  storageId: "",
  itemInfo: "",
  orgId: props.orgId
})
// 项目选择自动补全窗体名称
const itemTitle = ref('选择项目')
// 项目选择自动补全表格表头
const tableHeadList = ref(jsonStrInObj(prescriptionList))
// 项目选择自动补全表格数据
const tableBodyList = ref([])
// 项目选择自动补全字典数组
const dictArray = ref(['bill_item_class_dict', 'is_medical_insurance'])

// 表单校验
const rules = ref({
  groupNumber: [
    {required: true, validator: positiveNumberNotNull, trigger: "blur"}
  ],
  abidance: [
    {required: true, validator: positiveNumberNotNull, trigger: "blur"}
  ],
  num: [
    {required: true, validator: positiveNumberNotNull, trigger: "blur"}
  ],
  singleDosage: [
    {required: true, message: "单次用量不能为空", trigger: "change"}
  ],
  drugName: [
    {required: false, message: "药品不能为空", trigger: "change"}
  ],
  channel: [
    {required: true, message: "用药途径不能为空", trigger: "change"}
  ],
  performFreq: [
    {required: true, message: "执行频次不能为空", trigger: "change"}
  ],
})

// 组件挂载时添加事件监听
onMounted(() => {
  window.addEventListener('keydown',
    handleKeydown);
});
// 组件卸载时移除事件监听以避免内存泄漏
onUnmounted(() => {
  window.removeEventListener('keydown',
    handleKeydown);
});

function handleKeydown(event) {
  if (event.keyCode == "113") {
    event.preventDefault();//阻止浏览器默认事件
    handleAddDrug()
  }
}

/**
 * 打开西药明细事件
 * @param drugClassArrayParam
 * @param storageId
 */
function setDrugClassArray(drugClassArrayParam: any, storageId: string) {
  autoForm.value.drugClassArray = drugClassArrayParam
  autoForm.value.storageId = storageId
  trDisabled.value = true
}

/**
 * 批量选中
 */
function handleSelectionChange() {

}

/**
 * 途径点击事件
 */
function administrationInfoChange(e, index: number, _row: any) {
  const dict = toRaw(e)
  form.value.prescriptionItemList[index].channel = dict.dictValue
  // 途径为 皮试的话，将免皮试设置为不选中
  form.value.prescriptionItemList[index].noSkin = dict.dictValue !== "112";
  form.value.prescriptionItemList[index].isSkin = dict.dictValue !== "112" ? 'N' : 'Y';
}

/**
 * 频次点击事件
 */
function performFreqInfoChange(e: any, index: number) {
  const performFreqInfo = toRaw(e)
  form.value.prescriptionItemList[index].performFreq = performFreqInfo.freqId
  form.value.prescriptionItemList[index].performFreqInfo = performFreqInfo
  calculatedQuantityAndMoney(index)
}

/**
 * 计算数量 和金额
 */
function calculatedQuantityAndMoney(index: number) {
  // 最小剂量
  const singleDosageMin = form.value.prescriptionItemList[index].singleDosageMin
  // 实际开出剂量
  const singleDosage = form.value.prescriptionItemList[index].singleDosage
  // 包装数量
  const packageNumCalculate = form.value.prescriptionItemList[index].packageNumCalculate
  if (typeof singleDosageMin !== "undefined" && typeof singleDosage !== "undefined" && typeof packageNumCalculate !== "undefined") {
    // 天数
    const abidance = form.value.prescriptionItemList[index].abidance
    // 获取频次对应的服用次数
    const performTime = form.value.prescriptionItemList[index].performFreqInfo.performTime ?
      form.value.prescriptionItemList[index].performFreqInfo.performTime.split("-").length : 1
    // 计算实际开出的单次用量和最小剂量的商
    const num: number = Number(Math.ceil(singleDosage / singleDosageMin))
    const amount: number = Number(Math.ceil(performTime * num * abidance))
    // 列表中总数量
    let sumAmount: number = 1;
    // if (amount % packageNum > 1) {
    sumAmount = Number(Math.ceil(amount / packageNumCalculate))
    // }
    // 给总数量赋值
    form.value.prescriptionItemList[index].num = sumAmount
    // 给总价赋值
    form.value.prescriptionItemList[index].sumPrice = Number((sumAmount * form.value.prescriptionItemList[index].price).toFixed(2))
  }
}

/**
 * 单次剂量input失去焦点事件
 */
function inputBlur(index: number) {
  calculatedQuantityAndMoney(index)
}

/**
 * 直接修改数量事件
 * @param index
 */
function numInputBlur(index: number) {
  // 给总价赋值
  form.value.prescriptionItemList[index].sumPrice = Number(form.value.prescriptionItemList[index].num * form.value.prescriptionItemList[index].price).toFixed(2)
}


/**
 * 滴速点击事件
 */
function dripSpeedChange(e, _index: number, row: any) {
  const sysDropSpeedArr: any = toRaw(dictDataMap.value['sys_drop_speed'])
  const indexNum = sysDropSpeedArr.findIndex((sysDropSpeed: any) => {
    return sysDropSpeed.dictValue === e
  })
  if (indexNum > -1) {
    if (row.remarks) {
      let str = row.remarks + "," + sysDropSpeedArr[indexNum].dictLabel
      row.remarks = str;
    } else {
      row.remarks = sysDropSpeedArr[indexNum].dictLabel
    }
  }
}

/** 自动补全后台查询 */
function getListDrugItem(index:number) {
  if (autoForm.value.itemInfo) {
    autoForm.value.orgId = props.orgId
    // 来自otc门诊 只能开otc药品，1不能开，0能开
    autoForm.value.isOtc = props.isOtcOutpatient ? '1' : '0'
    autoPrescriptionList(autoForm.value).then(res => {
      // 打开自动补全弹出框
      itemAutomaticRefs.value[index].init()
      tableBodyList.value = res.data

    })
  } else {
    tableBodyList.value = []
  }
}

function parentHandleAddDrug() {
  handleAddDrugOk()
}

/**
 * 添加药品
 */
function handleAddDrug() {
  if (props.applyIsDisabled) {
    handleAddDrugOk()
  } else {
    return ElMessage.error("请先点击（处方新增）按钮后，再添加药品")
  }

}

function handleAddDrugOk() {
  (formRef.value as any).validate(valid => {
    if (valid) {
      if (form.value.prescriptionItemList.length > 0 &&
        form.value.prescriptionItemList[form.value.prescriptionItemList.length - 1].abidance > 7
        && !form.value.prescriptionItemList[form.value.prescriptionItemList.length - 1].remarks
      ) {
        return ElMessageBox.prompt(`${form.value.prescriptionItemList[form.value.prescriptionItemList.length - 1].drugName}
          药品用量大于7天，请填写超量说明`, '超量说明', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^[\s\S]+$/,
          inputErrorMessage: '超量说明不能为空',
        })
          .then(({value}) => {
            form.value.prescriptionItemList[form.value.prescriptionItemList.length - 1].remarks = value
            handleAddDrug()
          })
          .catch(() => {
            ElMessage.error("取消输入")
          })
      }
      if (form.value.prescriptionItemList.length >= 5) {
        return ElMessage.error("根据《处方管理办法》规定，为了规范用药，减少多药联用可能带来的不良反应，" +
          "每张处方不得超过 5 种药品，如需开药，请开具新处方。");
      }
      // 最大的组号
      let maxGroupNumber = 0
      if (form.value.prescriptionItemList.length > 0) {
        // 获取表格内最大的组号
        maxGroupNumber = Math.max.apply(Math, form.value.prescriptionItemList.map((item: any) => {
          return item.groupNumber
        }))
      }
      form.value.prescriptionItemList.push({
        // 是否免皮试 保存、修改时需要单独处理 true-> Y , false-> N
        noSkin: true,
        sumPrice: 0.00,
        price: 0.00,
        groupNumber: maxGroupNumber + 1,
        drugName: "",
        abidance: 1,
        num: 1,
        isShow: true,
        // 途径是否禁用
        channelDisabled: false,
        // 频次是否禁用
        performFreqDisabled: false
      })
      nextTick(() => {
        initInputDOM(form.value.prescriptionItemList.length - 1);
      });
    }
  })
}

function initInputDOM(index) {
  //获取id为table-form下的所有input 框
  const inputDoms = document.querySelectorAll(
    ".groupNumber .el-input__inner"
  )
  inputDoms[index].focus();
}

/**
 * 删除药品明细
 */
function handleDelete(index: number, _row: any) {
  ElMessageBox.confirm('删除后数据将会丢失，确定要继续操作吗？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    form.value.prescriptionItemList.splice(Number(index), 1)
  }).catch(() => {
    ElMessage.info("操作终止")
  })
}

/**
 * 明细行数据校验
 */
function itemValidate() {
  if (form.value.prescriptionItemList.length <= 0) {
    return ElMessage.error("请添加药品明细后，再增加")
  }
  (formRef.value as any).validate(valid => {
    if (valid) {
      let type = true;
      for (let i = 0; i < form.value.prescriptionItemList.length; i++) {
        const item = form.value.prescriptionItemList[i];
        if (item.abidance > 7 && !item.remarks) {
          type = false
          return ElMessageBox.prompt(`${item.drugName}
          药品用量大于7天，请填写超量说明`, '超量说明', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputPattern: /^[\s\S]+$/,
            inputErrorMessage: '超量说明不能为空',
          })
            .then(({value}) => {
              item.remarks = value
              itemValidate()
            })
            .catch(() => {
              ElMessage.error("取消输入")
            })
        } else {
          type = true
        }
      }
      if (type) {
        emits("itemSubmitOk", form.value.prescriptionItemList)
      }
    }
  })
}

/**
 * 根据 drugName 和 identicalInfoId 分组并合计 num
 */
function groupAndSum() {
  const groupedMap = new Map<string, any>();

  form.value.prescriptionItemList.forEach(item => {
    const key = `${item.drugName}-${item.identicalInfoId}`;
    if (groupedMap.has(key)) {
      const existingItem = groupedMap.get(key);
      existingItem.num += item.packSize === '2' ? item.num * item.packageNum : item.num;
    } else {
      groupedMap.set(key, {...item, num: item.packSize === '2' ? item.num * item.packageNum : item.num});
    }
  });
  return Array.from(groupedMap.values());
}

/**
 * 最终保存
 * @param prescriptionFormParam
 */
function saveIsOk(prescriptionFormParam: any) {
  for (let i = 0; i < form.value.prescriptionItemList.length; i++) {
    const item = form.value.prescriptionItemList[i];
    item.noSkin = item.noSkin ? 'Y' : 'N'
  }
  const groupAndSumList = groupAndSum();
  for (let i = 0; i < groupAndSumList.length; i++) {
    const item = groupAndSumList[i];
    //实际库存 - 已占用库存
    const stockNum = item.minQuantity - item.reductionAmount
    if (item.num > stockNum) {
      return ElMessage.error("药品【" + item.drugName + "】,开药数量大于【库存数量】，不能保存请重新填写数量后再提交")
    }
  }

  ElMessageBox.confirm('确定要进行处方保存操作吗？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 不代煎
    prescriptionFormParam.isDecoction = "1"
    prescriptionFormParam.repetition = 1
    prescriptionFormParam.prescriptionItemBoList = form.value.prescriptionItemList
    prescriptionFormParam.isUpdateDoctorId = "Y"
    addPrescriptionApply(prescriptionFormParam).then((res: any) => {
      emits("submitOk")
      prescPrint({applyId: res.msg, orgId: props.orgId})
      ElMessage.success("处方保存成功")
    })
  }).catch(() => {
    ElMessage.info("操作终止")
  })
}

/**
 * 处方打印
 * @param row
 */
function prescPrint(row: any) {
  let url = "/business/prescriptionApply/prescPrint";
  const formData = new FormData()
  formData.append("applyId", row.applyId)
  formData.append("orgId", row.orgId)
  // pdf打印 、打印预览
  proxy.$printPdfPublic(url, formData).then(res => {
    if (res) {
      // objectUrl.value = URL.createObjectURL(res)
      // nextTick(() => {
      // printPreviewRef.value.init(objectUrl.value)
      // })
    } else {
      console.error('打印失败')
    }
  })
}

// 清空药品列表
function emptyDrugList(type: boolean) {
  if (type) {
    ElMessageBox.confirm('重置后未保存的数据将会丢失，确定要继续操作吗？',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      form.value.prescriptionItemList = []
    }).catch(() => {
      ElMessage.info("操作终止")
    })
  } else {
    form.value.prescriptionItemList = []
  }
}

/** 项目名称自动补全检索 */
function itemNameInput(e: any, index: number, _row: any) {
  autoForm.value.itemInfo = e
  getListDrugItem(index)
}

/** 主表行点击事件 */
function applyRowClick(row: any) {
  const rows = toRaw(row)
  form.value.prescriptionItemList = []
  const params = {
    applyId: rows.applyId,
    orgId: props.orgId
  }
  listPrescriptionItem(params).then((res: any) => {
    assembleItemFun(res.data,rows);
  })
}


/** 历史处方主表行点击事件 */
function historyApplyQuoteFun(row: any) {
  const rows = toRaw(row)
  form.value.prescriptionItemList = []
  const params = {
    applyId: rows.applyId,
    orgId: props.orgId,
    implementDept: rows.implementDept,
    itemClass: rows.itemClass
  }
  historyApplyQuote(params).then((res: any) => {
    assembleItemFun(res.data,rows);
  })
}

/**
 * 组装药品列表
 * @param data 后台返回数据
 * @param rows 前台点击的行数据
 */
function assembleItemFun(data: any,rows: any) {
  // 是否 是从历史处方引入点击
  if (rows.historyApplyQuote) {
    trDisabled.value = true
  } else {
    trDisabled.value = rows.chargeFlag === "1"
  }
  data.forEach((item: any, index) => {
    console.log("item", item)
    item.itemId = ""
    item.isShow = true
    item.packageNumCalculate = item.packSize === "1" ? 1 : item.packageNum
    // 设置免皮试 如果是不能编辑状态 noSkin 设置为 true或者false，用于多选按钮选中，否则设置为 Y或者N，用于字典显示
    item.noSkin = trDisabled.value === true ? item.noSkin === "Y" : item.noSkin
    item.singleUnitName = dictStore.getMateDictInfo(dictDataMap.value['dose_unit'], item.singleUnit).dictLabel
    const unit = item.packSize === "1" ? item.minUnits : item.packageUnits
    item.unitName = dictStore.getMateDictInfo(dictDataMap.value['spec_unit'], unit).dictLabel
    if (rows.historyApplyQuote) {
      item.createTime = undefined
      item.createBy = ""
      item.createByName = ""
      item.updateTime = undefined
      item.updateBy = ""
      item.updateByName = ""
    }

    form.value.prescriptionItemList.push(item)
    // 自动补全组件赋值
    nextTick(()=>{
      if (itemAutomaticRefs.value[index]) {
        itemAutomaticRefs.value[index].setItemName(item.drugName)
      }
    })
  })
}


/** 项目列表行点击事件 */
function rowClick(e: any, index: number, row: any) {
  itemAutomaticRefs.value[index].setItemName(e.drugName)
  itemAutomaticRefs.value[index].closePopover()
  row.isShow = true
  row.sumPrice = 0.00
  row.singleDosageMin = e.dose
  row.singleDosage = e.dose
  row.singleUnitName = e.doseUnitsName
  row.singleUnit = e.doseUnits
  row.unitName = e.unitsName
  row.minUnits = e.minUnits
  row.packageUnits = e.packageUnits
  row.packageSpec = e.packageSpec
  row.minSpec = e.minSpec
  row.packSize = e.packSize
  row.firmName = e.firmName
  row.firmId = e.firmId
  row.drugName = e.drugName
  row.drugCode = e.drugCode
  row.price = e.price
  row.abidance = 1
  row.sumPrice = e.price * 1
  row.batchNo = e.batchNo
  row.packageNum = e.packageNum
  row.quantity = e.quantity
  row.minQuantity = e.minQuantity
  row.reductionAmount = e.reductionAmount
  row.packageNumCalculate = e.packSize === "1" ? 1 : e.packageNum
  row.identicalInfoId = e.identicalInfoId
  row.tradePrice = e.tradePrice
  row.priceId = e.drugPriceId
  if (!row.channel) {
    row.channel = e.channel
  }
  if (!row.performFreq) {
    row.performFreq = e.performFreq
    row.performFreqInfo = dictStore.getAppointPerformFreqInfo(e.performFreq)
  }
  row.drugInfoId = e.drugInfoId
  row.sort = index + 1
  inputBlur(index)
  tableBodyList.value = []
}

// 组号input焦点消失事件
function groupNumberBlur(index: number, row: any) {
  // 获取list所有行
  const rows = form.value.prescriptionItemList
  // 当前行行号
  const groupNumber = Number(row.groupNumber)
  // 当前行的前一行
  const previousRow = rows[index - 1]
  if (previousRow) {
    const previousRowGroupNumber = previousRow.groupNumber;
    if (previousRowGroupNumber === groupNumber) {
      row.channel = previousRow.channel
      row.performFreq = previousRow.performFreq
      performFreqInfoChange(dictStore.getAppointPerformFreqInfo(previousRow.performFreq), index)
      row.channelDisabled = true
      row.performFreqDisabled = true
    } else {
      row.channelDisabled = false
      row.performFreqDisabled = false
    }
    const groupNumberIndex = form.value.prescriptionItemList.findIndex((item: any) => {
      return groupNumber === item.groupNumber
    })
    // if (groupNumberIndex > -1 && groupNumber !== previousRowGroupNumber) {
    //     ElMessage.error("相同的组号不能相邻，请重新输入")
    // }
  }

}

/*********************************************  模板数据引用  *********************************************/
function templateQuote(list: any) {
  trDisabled.value = true
  list.forEach((item: any) => {
    item.isShow = true
    item.drugName = item.drugName || item.itemName
    item.drugCode = item.drugCode || item.itemCode
  })
  form.value.prescriptionItemList = list
}

defineExpose({
  emptyDrugList,
  setDrugClassArray,
  parentHandleAddDrug,
  itemValidate,
  applyRowClick,
  saveIsOk,
  templateQuote,
  historyApplyQuoteFun
})

</script>

<style scoped>
:deep(.el-input-group__append) {
  padding: 0 5px;
  width: 40px;
}

:deep(.el-input__wrapper .el-input__inner) {
  margin-right: -15px;
}

:deep(.el-form-item__content) {
  margin-bottom: 6px;
}

:deep(.el-form-item__error) {
  font-size: 11px;
  color: #ff0000;
}

.noSkin-checkbox {
  margin-left: 15px;
}

:deep(.el-input-group__prepend) {
  padding-left: 5px;
  padding-right: 5px;
}
</style>
